<template>
  <div>
    <a-layout-header class="header flex">
      <!-- logo -->
      <div class="logo min-w-[280px] pr-4 flex items-center" @click="goHome">
        <img :src="logoIcon || LogoIcon" class="h-8 mr-2" />
        {{ `${appName} | ${appStore.CURRENT_ROUTE_NAME || '门户'} ` }}
      </div>
      <!-- menu -->
      <div class="flex-1 overflow-hidden relative flex justify-between items-center pr-8">
        <a-menu
          v-if="!['/', '/report'].includes(currentRoutePath)"
          ref="menuRef"
          v-model:selected-keys="selectedKeys"
          mode="horizontal"
          :items="menus"
          class="menu-top-style"
          @select="onMenuClick"
        />
        <SelectOrg v-if="isEYE" />
      </div>
      <!-- setting -->
      <a-space class="header-left pl-4" size="middle">
        <div class="header-left-item" @click="refresh">
          <!-- 刷新 -->
          <RedoOutlined class="text-base text-white" />
        </div>
        <div class="header-left-item">
          <!-- 消息 -->
          <Notification />
        </div>
        <div class="header-left-item" @click="goHome">
          <!-- 首页 -->
          <HomeOutlined class="text-base text-white" />
        </div>
        <div class="header-left-item" @click="showSetting">
          <!-- 设置 -->
          <SettingOutlined class="text-base text-white" />
        </div>
        <a-dropdown>
          <div class="flex items-center">
            <a-avatar class="cursor-pointer" :size="28" :src="avatarMan" />
            <div class="ml-1 text-white cursor-pointer truncate w-16">{{ userStore.empName }}</div>
          </div>
          <template #overlay>
            <a-menu class="w-32">
              <a-menu-item key="1" @click="onShowPwd"><span class="px-4">修改密码</span> </a-menu-item>
              <template v-if="isInBox">
                <a-menu-divider />
                <a-menu-item key="5" @click="onSettingPrint"><span class="px-4">打印设置</span></a-menu-item>
                <a-menu-divider />
                <a-menu-item key="4" @click="onMinWindow"><span class="px-4">最小化</span></a-menu-item>
              </template>
              <a-menu-divider />
              <a-menu-item key="2" @click="onLoginOut"><span class="text-red-500 px-4">退出登录</span></a-menu-item>
              <template v-if="isInBox">
                <a-menu-divider />
                <a-menu-item key="3" @click="onCloseWindow"><span class="text-orange-500 px-4">退出系统</span></a-menu-item>
              </template>
            </a-menu>
          </template>
        </a-dropdown>
      </a-space>
    </a-layout-header>
    <a-modal v-model:open="pwdModalOpen" centered title="修改密码" @ok="onChangePwd">
      <a-form :model="formState" class="p-6" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="用户名">
          {{ userStore.empName || '-' }}
        </a-form-item>
        <a-form-item label="旧密码" name="pwd" :rules="[{ required: true, message: '请输入旧密码' }]">
          <a-input v-model:value="formState.pwd" placeholder="旧密码" />
        </a-form-item>
        <a-form-item label="新密码" name="newPwd" :rules="[{ required: true, message: '请输入新密码' }]">
          <a-input v-model:value="formState.newPwd" placeholder="新密码" />
        </a-form-item>
        <a-form-item label="确认新密码" name="newPwd2" :rules="[{ required: true, message: '请输入新密码' }]">
          <a-input v-model:value="formState.newPwd2" placeholder="确认新密码" />
        </a-form-item>
      </a-form>
    </a-modal>
    <SettingDrawer :open="isShowSetting" @close="showSetting" />
  </div>
</template>
<script setup>
import { onMounted, ref, watchEffect } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { SettingOutlined, HomeOutlined, RedoOutlined } from '@ant-design/icons-vue'
import useUserStore from '@/store/user'
import useAppStore from '@/store/app'
import avatarMan from '@/assets/images/avatar-man.png'
import { post } from '@/utils/request'
import { getSystemConfig } from '@/utils/systemConfig'
import LogoIcon from '@/assets/images/logo.png'
import useMenu from '@/hooks/useMenu'
import Notification from './Notification'
import SettingDrawer from './SettingDrawer.vue'

const router = useRouter()
const appStore = useAppStore()
const userStore = useUserStore()

const isShowSetting = ref(false)
const isInBox = ref(false)
const isEYE = ref(false)
const menuRef = ref(null)
const pwdModalOpen = ref(false)
const formState = ref({})
const currentRoutePath = ref('')
const selectedKeys = ref([])
const { menus } = useMenu()
const onMenuClick = (menu) => {
  if (!appName.value || appName.value === '医疗信息系统') {
    appStore.loginOut()
    return
  }
  if (menu.item.title) {
    document.title = appName.value + ' - ' + menu.item.title
  }
  router.push(menu.key)
}
//页面刷新时菜单自动选中当前路由
watchEffect(() => {
  // const activeMenu = router.currentRoute.value.meta.activeMenu //指定高亮菜单
  const path = router.currentRoute.value.path
  currentRoutePath.value = path
  const fullPath = router.currentRoute.value.fullPath
  if (path === '/report' || fullPath.indexOf('?routerType') !== -1) {
    selectedKeys.value = [fullPath]
  } else {
    selectedKeys.value = [path]
  }
})
watch(
  () => appStore.CURRENT_ROUTE_NAME,
  (val) => {
    if (['视光配镜', '屈光发育', '角塑管理', '视力筛查'].includes(val)) {
      isEYE.value = true
    } else {
      isEYE.value = false
    }
  },
  { immediate: true }
)
const showSetting = () => {
  isShowSetting.value = !isShowSetting.value
}

const onChangePwd = async () => {
  if (formState.value.newPwd !== formState.value.newPwd2) return message.error('两次密码不一致')
  formState.value.empId = userStore.empId
  const { code, msg } = await post('/common/util/changeThePassword', formState.value)
  if (code !== 0) return message.error(msg || '修改失败')
  message.success('修改成功，请重新登录')
  onLoginOut()
}
const onShowPwd = () => {
  pwdModalOpen.value = true
  formState.value = {}
}
const onLoginOut = () => {
  appStore.loginOut()
}
watch(
  () => userStore.empName,
  (val) => {
    !val && onLoginOut()
  },
  { immediate: true }
)
const goHome = () => {
  appStore.CURRENT_ROUTE_NAME = '门户'
  router.push({ path: '/' })
}
const appName = ref('医疗信息系统')
const onCloseWindow = async () => {
  window.openExe?.closeWindow()
  // if (window.openExe) {
  //   window.openExe?.closeWindow()
  // } else {
  //   const isConfirm = await cofirmModal({ title: '提示', content: '确定关闭网页吗？' })
  //   if (!isConfirm) return
  //   window.location.href = 'about:blank'
  //   window.close()
  // }
}
const onMinWindow = () => {
  window.openExe?.minWindow()
}
const onSettingPrint = () => {
  window.openExe?.openPrinterSet()
}
const logoIcon = ref('')
onMounted(() => {
  // if (!getSystemConfig('HISNAME')) {
  //   router.push({ path: '/login' })
  // }
  appName.value = getSystemConfig('HISNAME') || '医疗信息系统' //系统名称
  logoIcon.value = getSystemConfig('HOSPITAL_LOGO_URL') //logo
  setIcon(logoIcon.value)
  isInBox.value = !!window.openExe
})
const setIcon = (icoUrl) => {
  const link = document.querySelector("link[rel*='icon']") || document.createElement('link')
  link.type = 'image/x-icon'
  link.rel = 'shortcut icon'
  link.href = icoUrl
  document.getElementsByTagName('head')[0].appendChild(link)
}
const refresh = () => {
  location.reload()
}
</script>
<style scoped lang="less">
.header {
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 40px;
  padding: 0 24px;
  line-height: 40px;
  background-color: var(--primary-color);
  box-shadow: rgba(0, 0, 0, 0.1) 0px 8px 16px;

  .logo {
    color: #fff;
    font-weight: 600;
    font-size: 18px;
    font-family: Microsoft Yahei, PingFang SC, -apple-system, Arial, sans-serif;
    cursor: pointer;
  }

  .header-left {
    display: flex;
    justify-content: space-between;

    .header-left-item {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 32px;
      height: 32px;
      background: #ffffff25;
      border-radius: 8px;
      cursor: pointer;

      &:hover {
        background: #ffffff45;
      }
    }
  }
}
.header-menu-more {
  @apply absolute right-4 top-0 h-full flex justify-center items-center p-2 cursor-pointer;
  span:hover {
    background-color: #00000020;
    border-radius: 4px;
  }
}
.shadow-left {
  &::before {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 9;
    width: 6px;
    height: 43px;
    background: linear-gradient(to right, rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0));
    content: '';
  }
}
.shadow-right {
  &::before {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 9;
    width: 6px;
    height: 43px;
    background: linear-gradient(to right, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.3));
    content: '';
  }
}
.menu-top-style {
  height: 100%;
  margin-right: 54px;
  overflow: auto;
  color: #ffffffdd;
  background-color: transparent;
  border-bottom: none;
  &::-webkit-scrollbar {
    width: 0;
    height: 0;
  }
}
&:deep(.ant-menu-submenu) {
  padding: 0 8px;
  .ant-menu-submenu-title {
    padding: 0 28px;
    color: #fff !important;
  }
  &.ant-menu-submenu-selected {
    color: #fff !important;
    background-color: #00000040 !important;
    border-radius: 4px;
  }
}
&:deep(.ant-menu) {
  .ant-menu-item {
    padding: 0 28px;
  }
  .ant-menu-item-active,
  .ant-menu-submenu-active {
    color: #fff !important;
    background-color: #00000020;
  }
  .ant-menu-submenu-title {
    color: #fff !important;
  }
  .ant-menu-item-selected,
  .ant-menu-submenu-selected {
    color: #fff !important;
    background-color: #00000040;
  }
}
</style>
